from django.shortcuts import render, reverse
from django.http import HttpResponse, HttpResponseRedirect
from models_user.models import *

# Create your views here.


class Login:

    def __init__(self, args):   # args{'name':'xxx','pswd':'zzzz'}
        self.args = args

    def false_or_true(self):
        name = self.args['name']
        pswd = self.args['pswd']
        try:
            self.user = User.objects.get(name=name)     # 只能提到到一个对像，其他情况报错
        except User.DoesNotExist:
            return '没有这个用户', None
            
        if self.user.pswd == pswd:
            return '登陆成功', self.user.id
        else:
            return '密码错误', None

    def user_duty(self):
        # self.user.duty.values_list('name')
        return list(self.user.duty.values_list('duty'))

    
'''
class Login(View):

    def get(self,request)

'''


def login(request):
    if request.method == 'GET':
        context = {'mes': 'Please sign in'}
        return render(request, 'login/login.html', context)
    elif request.method == 'POST':
        info = dict(request.POST)

        '''{'name':'xxx','pswd':'zzzz'}'''

        info_dict = dict()
        info_dict['name'] = info['name'][0]
        info_dict['pswd'] = info['pswd'][0]
        login_obj = Login(info_dict)
        status = login_obj.false_or_true()[0]

        if status == '登陆成功':
            request.session['id'] = login_obj.false_or_true()[1]
            request.session['name'] = info['name'][0]
            request.session['duty'] = login_obj.user_duty()
            return HttpResponseRedirect(reverse('index:index'))
        else:
            context = {'mes': status}
            return render(request, 'login/login.html', context)

    return HttpResponse('OK')

